package v.e.mapper

import kotlinx.coroutines.*
import java.io.File
import java.lang.RuntimeException
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
import javax.xml.parsers.SAXParserFactory

fun main(args: Array<String>) = runBlocking {
    val classLoader = Thread.currentThread().contextClassLoader

//    print(classLoader.getResource("mappers.csv").file)

    val file = File(classLoader.getResource("mappers.csv").file)
    var entitiesFileList = mutableListOf<String>()
    var mysqlEntitiesFileList = mutableListOf<String>()
    var FileMap = mutableMapOf<String,String>()
    file.readLines()
        .forEach {
            if (it.indexOf("文件名,路径") > -1) {
                return@forEach
            }

            val filename = it.split(",").reversed().joinToString(separator = "\\")

            if (filename.indexOf("mysql") > -1) {
                mysqlEntitiesFileList.add(filename)
            } else {
                entitiesFileList.add(filename)
            }

        }
    entitiesFileList.forEach {
        val file = File(it)
        val kingbasePath = File(file.parent,"\\kingbase")
        if(!kingbasePath.exists()){
            kingbasePath.mkdir()
        }
        val destFile = Paths.get(kingbasePath.path +File.separatorChar + file.name)
        Files.copy(Paths.get(it),destFile, StandardCopyOption.REPLACE_EXISTING)
        val handler = MapperFileSaxHandler(destFile.toString(),false)
        doSax(handler)
        if(FileMap.containsKey(handler.getNamespace())){
            throw RuntimeException("${handler.getNamespace()} is exist.")
        }
        FileMap.put(handler.getNamespace(),handler.getFilename())
    }

    mysqlEntitiesFileList.forEach {
        val file = File(it)
        val handler = MapperFileSaxHandler(file.path,true)
        doSax(handler)
        FileMap.get(handler.getNamespace())

    }


}

fun doSax(handler:MapperFileSaxHandler){
    val sAXParserFactory = SAXParserFactory.newInstance()
    val sAXParser = sAXParserFactory.newSAXParser()
    sAXParser.parse(
        handler.getFilename(),
        handler
    )
}


